import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class leetcode18 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret=new ArrayList<>();
        Arrays.sort(nums);
        for(int i=0;i<nums.length-3;){
            for(int j=i+1;j<nums.length-2;){
                int left=j+1;
                int right=nums.length-1;
                while(left<right){
                    List<Integer> list=new ArrayList<>();
                    int sum=nums[left]+nums[right];
                    long t=(long)target-nums[i]-nums[j];
                    if(sum>t){
                        right--;
                        while(left<right&&nums[right]==nums[right+1]){
                            right--;
                        }
                    }else if(sum<t){
                        left++;
                        while(left<right&&nums[left]==nums[left-1]){
                            left++;
                        }
                    }else{
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[left]);
                        list.add(nums[right]);
                        ret.add(list);
                        right--;
                        while(left<right&&nums[right]==nums[right+1]){
                            right--;
                        }
                        left++;
                        while(left<right&&nums[left]==nums[left-1]){
                            left++;
                        }
                    }
                }
                j++;
                while(j<nums.length-2&&nums[j]==nums[j-1]){
                    j++;
                }
            }

            i++;
            while(i<nums.length-3&&nums[i]==nums[i-1]){
                i++;
            }
        }
        return ret;
    }
}
